package org.autumn.design.single;

public class Singleton {

    private volatile static Singleton instance;
    private Singleton() {
    }

    public static Singleton getInstance() {
        // below code will go wrong    if (instance == null){}
        if (instance == null){
            synchronized (Singleton.class){
                if (instance == null){
                    // 这里代码如果出现指令重排 就会先赋值 在执行构造方法
                    // 导致第一行代码判断不为空 将没有初始化的对象返回出去
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        System.out.println(Singleton.getInstance());
        System.out.println(Singleton.getInstance());
        System.out.println(Singleton.getInstance());
        System.out.println(Singleton.getInstance());
    }
}
